package com.wenhua.junshao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wenhua.junshao.common.R;
import com.wenhua.junshao.entity.Category;
import com.wenhua.junshao.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("category")
@Slf4j
@RestController
public class CategoryController {

    @Autowired
    private CategoryService categoryService;


    /**
     * 新增分类
     */
    @PostMapping()
    public R<String> save(@RequestBody Category category) {
        log.info("category:{}, category");
        categoryService.save(category);
        return R.success("添加成功");

    }

    @GetMapping("page")
    public R<Page<Category>> page(long page, long pageSize) {
        //构造分页器
        final Page<Category> pageInfo = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加排序条件
        queryWrapper.orderByAsc(Category::getSort);
        //分页查询
        categoryService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 根据id删除分类
     */
    @DeleteMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> delete(Long id) {
        log.info("删除分类，id为：{}", id);
        //categoryService.removeById(id);
        categoryService.remove(id);
        return R.success("删除分类成功");
    }

    /**
     * 根据id修改分类信息
     */
    @PutMapping
    public R<String> update(@RequestBody Category category) {

        categoryService.updateById(category);

        return R.success("修改成功");
    }


    @GetMapping("list")
    public R<List<Category>> list(Integer type) {
        //创建条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.eq(type != null, Category::getType, type);
        //添加排序条件
        queryWrapper.orderByDesc(Category::getSort);
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }
}
